package vn.mahjonggame.game.request;

import vn.mahjonggame.game.Mahjong;
import vn.mahjonggame.game.MahjongExtension;
import vn.mahjonggame.metadata.GameActionType;
import vn.mahjonggame.metadata.Player;
import vn.mahjonggame.metadata.MObject;
import vn.mahjonggame.metadata.RoomVarName;
import vn.mahjonggame.zone.MahjongZoneExtension;
import vn.mahjonggame.zone.request.CreateMahjongRoomRequestHandler;

import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;

public class CreateReplayRoomHandler extends BaseClientRequestHandler {

	@Override
	public void handleClientRequest(User user, ISFSObject params) {		
		int previousPosition = params.getInt(MObject.position.toString());		
		Room lastJoinedRoom = user.getLastJoinedRoom();
		
		MahjongZoneExtension parentExtension = (MahjongZoneExtension)getParentExtension();
		
		int playeMode = lastJoinedRoom.getVariable(RoomVarName.playMode.toString()).getIntValue();
		String roomName = lastJoinedRoom.getName();
		int roomBet = lastJoinedRoom.getVariable(RoomVarName.roomBet.toString()).getIntValue();		
		String roomPassword = lastJoinedRoom.getPassword();
		
		params.putInt(RoomVarName.playMode.toString(), playeMode);
		params.putUtfString(RoomVarName.roomName.toString(), roomName);
		params.putInt(RoomVarName.roomBet.toString(), roomBet);
		if(roomPassword != null){
			params.putUtfString(RoomVarName.roomPassword.toString(), roomPassword);
		}
		
		/*
		 * Remove room
		 */
		getApi().removeRoom(lastJoinedRoom);
		
		/*
		 * Create the new room
		 */
		CreateMahjongRoomRequestHandler createMahjongRoomRequestHandler = new CreateMahjongRoomRequestHandler();
		createMahjongRoomRequestHandler.createMahjongRoom(parentExtension, user, params);
		
		SFSObject response = new SFSObject();
		response.putInt(MObject.position.toString(), previousPosition);
		
		SFSObject roomConfig = new SFSObject();
		roomConfig.putInt(RoomVarName.playMode.toString(), playeMode);
		roomConfig.putUtfString(RoomVarName.roomName.toString(), roomName);
		roomConfig.putInt(RoomVarName.roomBet.toString(), roomBet);		
		roomConfig.putInt(RoomVarName.roomPassword.toString(), roomBet);
		
		send(GameActionType.createReplayRoom.toString(), response, user);			
	}
}